package com.huwei.filter;

import java.nio.charset.Charset;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import com.huwei.constant.JsonResult;
import com.huwei.constant.ResultErrorConstant;
import com.huwei.util.BeanUtil;
import com.huwei.util.CheckCodeUtil;
import com.huwei.util.RedisUtil;
import com.huwei.util.CheckCodeUtil.CheckCodeVo;

import lombok.extern.slf4j.Slf4j;

/**
 * 验证码校验
 * @author huwei
 */
@Slf4j
@Component
public class CheckCodeIntercept implements HandlerInterceptor{
	

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String key = request.getParameter("checkCodeKey");
		if(Objects.isNull(key)) {
			IOUtils.write(
					JsonResult.failed("checkCodeKey can not is null"
							, ResultErrorConstant.CHECK_CODE_KEY_MISS).getBytes()
					, response.getWriter() ,Charset.forName("UTF-8"));
			return false;
		}
		
		//从redis缓存中获取验证码
		RedisUtil redisUtil = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext()).getBean(RedisUtil.class);
		String ccvJson = (String)redisUtil.opsForString().get(key);
		if(Objects.isNull(ccvJson)) {
			IOUtils.write(
					JsonResult.failed("check code unexist,Please get the check code"
							, ResultErrorConstant.CHECK_CODE_MISS).getBytes()
					, response.getWriter() ,Charset.forName("UTF-8"));
			return false;
		}
		
		CheckCodeUtil.CheckCodeVo ccv = BeanUtil.toBean(ccvJson, CheckCodeVo.class);
		String checkCode = request.getParameter("checkCode");
		if(ccv.getCodes().size() == 1) {
			if(Objects.nonNull(ccv.getResultMap().get(checkCode))) {
				//删除验证码
				redisUtil.delKey(key);
				return true;
			}
		}
		else {
			//删除验证码
			redisUtil.delKey(key);
			log.debug("___ other check code type and going to check ____");
			return true;
		}
		
		IOUtils.write(JsonResult.failed("check code is error ,please again ", ResultErrorConstant.CHECK_CODE_MISS).getBytes()
				, response.getWriter() ,Charset.forName("UTF-8"));
		return false;
	}
	
}
